const { logger } = require("../config/logConfig")
const Category = require("../models/category")
const utils = require('../config/utils')
const { Op, QueryTypes } = require("sequelize")
const { validationResult } = require("express-validator")
const sequelize = require("../config/database")

// 分类列表
async function categoryList (req, res) {
  let condition = utils.listSelect(req.body)
  let pageObj = utils.pageSelect(req.body)
  try {
    const category = await Category.findAndCountAll({
      offset: pageObj.skip,
      limit: pageObj.limit,
      where: condition,
      order: [['seq', 'ASC']],
      distinct: true,
      attributes: {
        exclude: ["createdAt", "updatedAt"],
      }
    })
    if (!category) {
      utils.responseContent(res, 'OK', 200, data = { list: [], total: 0, pageSize: 10, pageNum: 1 })
    }
    utils.responseContent(res, 'OK', 200, data = {
      list: category.rows,
      pageNum: (pageObj.skip / pageObj.limit) + 1,
      pageSize: pageObj.limit,
      total: category.count
    })
  } catch (error) {
    logger.error(error)
    res.status(500).json({ msg: '获取分类列表失败', code: 500 })
  }
}

// 分类新增
async function categoryAdd (req, res) {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    for (var i = 0; i < errors.array().length; i++) {
      return res.status(400).json({ msg: errors.array()[i].msg, code: 0 });
    }
  }
  const { category_name, seq, stats, rmk = '' } = req.body
  try {
    logger.info(req)
    const count = await Category.count()
    let id
    if (count === 0) {
      // 如果是首次创建 则使用随机生成的 ID
      const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
      id = `1120${ randomNum }`
    } else {
      // 不是首次创建
      const [category] = await sequelize.query(`SELECT category_name, seq FROM Categories WHERE category_name = '${ category_name }' OR seq = ${ seq }`, { type: QueryTypes.SELECT })
      if (category) { // 并且不含有此分类名称且存在已经排序了的序号
        let msg = category.category_name === category_name ? `分类名称:${ category_name }已经存在` : `排序序号:${ seq }已经存在`
        return res.status(200).json({ msg, code: 500 })
      } else {
        // 获取第一条数据的ID，并在此基础上递增生成后续数据的 ID
        const max_id = await Category.findOne({ order: [['id', 'DESC']] })
        const maxId = parseInt(max_id.id) // 获取最大ID的数值部分
        id = maxId + 1
      }
    }
    await sequelize.query(
      `
      INSERT INTO Categories ( id, category_name, seq, stats, rmk, ctime, mtime, createdAt, updatedAt )
      VALUES
        ( 
          :id,
          :category_name,
          :seq,
          :stats,
          :rmk,
          :ctime,
          :mtime,
          NOW(),
          NOW()) 
        ON DUPLICATE KEY UPDATE id = id + 1;
    `,
      {
        type: QueryTypes.INSERT,
        replacements: {
          id: id,
          category_name: category_name,
          seq: seq,
          stats: stats,
          rmk: rmk, // 添加 rmk 参数
          ctime: Date.now(),
          mtime: Date.now(),
        }
      }
    )
    res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    logger.error(error)
    res.status(200).json({ msg: '新增分类标签失败', code: 500 })
  }
}
/**
 * 编辑
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
async function categoryUpd (req, res) {

  const { id, category_name, seq, stats, rmk } = req.body
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      for (var i = 0; i < errors.array().length; i++) {
        return res.status(400).json({ msg: errors.array()[i].msg, code: 0 });
      }
    }
    const [category] = await sequelize.query(`
        SELECT category_name, seq FROM Categories WHERE (category_name = :category_name OR seq = :seq) AND id != :id;
      `, {
      type: QueryTypes.SELECT,
      replacements: {
        category_name: category_name,
        seq: seq,
        id: id
      }
    });
    if (category) { // 并且不含有此分类名称且存在已经排序了的序号
      let msg = category.category_name === category_name ? `分类名称:${ category_name }已经存在` : `排序序号:${ seq }已经存在`
      return res.status(200).json({ msg, code: 500 })
    }
    try {
      await sequelize.query(`
      UPDATE Categories SET
        category_name = :categoryName,
        seq = :seq,
        stats = :stats,
        rmk = :rmk,
        mtime = :mtime,
        updatedAt = NOW()
      WHERE
        id = :id;
      `, {
        type: QueryTypes.INSERT,
        replacements: {
          id: id,
          categoryName: category_name,
          seq: seq,
          rmk: rmk,
          stats: stats,
          ctime: Date.now(),
          mtime: Date.now(),
        }
      })
      res.status(200).json({ msg: 'OK', code: 0 })
    } catch (error) {
      res.status(200).json({ msg: '编辑分类标签失败', code: 500 })
    }
  } catch (error) {
    logger.error(error)
    res.status(200).json({ msg: '编辑分类标签失败', code: 500 })
  }
}
/**
 * 详情
 * @param {*} req 
 * @param {*} res 
 */
async function categoryDetail (req, res) {
  const { id } = req.query
  try {
    const [category] = await sequelize.query(`SELECT category_name, seq, rmk, id, stats FROM Categories WHERE id = :id`, {
      type: QueryTypes.SELECT,
      replacements: {
        id
      }
    })

    console.log(category);
    if (category === null) {
      res.status(200).json({ msg: '查询分类标签失败', code: 0 })
    } else {
      res.status(200).json({ msg: 'OK', code: 0, data: category })
    }
  } catch (error) {
    res.status(200).json({ msg: error, code: 0 })
  }
}
async function isCategoryExists (categoryId) {
  const category = await Category.findOne({ where: { id: categoryId } });
  return category
}
module.exports = { categoryList, categoryAdd, isCategoryExists, categoryUpd, categoryDetail }
